// src/directives/loading.ts
import type{ Directive } from 'vue';
import { useAppStore } from '@/stores/app';

export const vLoadingFinish: Directive = {
  mounted(el, binding) {
    const appStore = useAppStore();
    
    // 监听路由组件挂载完成
    const observer = new MutationObserver(() => {
      // 当组件内容发生变化时，认为加载完成
      appStore.setLoading(false);
      observer.disconnect();
    });

    // 开始观察子节点的变化
    observer.observe(el, {
      childList: true,
      subtree: true,
      attributes: true,
      characterData: true
    });

    // 设置超时保护，确保loading最终会被关闭
    setTimeout(() => {
      appStore.setLoading(false);
      observer.disconnect();
    }, 5000); // 5秒超时
  },
  unmounted() {
    // 确保组件卸载时也关闭loading
    const appStore = useAppStore();
    appStore.setLoading(false);
  }
};